/**
 *  hw_irq.c - Hardware interfaces for interruption.
 *
 *  Copyright (C) 2008  ZhangHu
 *  All rights reserved.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *  E-MAIL: anmnmnly@gmail.com
 */


#include "regdef.h"
#include "hw_irq.h"
#include "include/irq.h"
#include "include/core.h"

/**
 * init_tick - select a timer for OS tick
 * @return:
 *
 * @notes: Initialize time5, clock cycle is 10ms.
 */
void init_tick(void) {
    isr_install(SYS_TIMER, 0, systick);
    rINTMSK &= 0x03FFFEFF;  /* unmask timer5 interrupt */

    rTCFG0 &= 0xFF00FFFF;   /* prescaler value of timer5 is 200 */
    rTCFG0 |= 0x00C80000;

    rTCFG1 &= 0xFF0FFFFF;
    rTCFG1 |= 0x00200000;   /* MUX input for PWM Timer5 is 1/8 */

    rTCNTB5 = 0x100;

    rTCON &= 0xF0FFFFFF;
    rTCON |= 0x02000000;    /* manual update timer5 */

    rTCON &= 0xF0FFFFFF;
    rTCON |= 0x01000000;    /* timer5 start */
    rTCON |= 0x04000000;    /* timer5 autoload */
}

/**
 * get_isr_num - Get the interrupt number, when interrupt occured.
 * @return: The serial number of active interruption.
 *
 * @notes: The serial number depends on specifical CPU.
 */
uword_t get_isr_num(void) {
    uword_t tmp;
    uword_t renum = 0;

    tmp = rI_ISPR;
    while(tmp != 0) {
        tmp >>= 1;
        renum++;
    }
    return renum - 1;
}

/**
 * isr_after_handle - clean something when interruption had handled.
 * @return:
 *
 * @notes: we shoulde rewrite this routine for Different CPU.
 */
void isr_after_handle(uword_t isr_num) {
    uword_t tmp = 1;

    while(isr_num-- > 0) {
        tmp <<= 1;
    }
    rI_ISPC |= tmp;
}

